Andrwyw home archives categories

编写:Andrwyw
项目:Android Training中文版
原文:http://developer.android.com/training/gestures/scroll.html

Scroll手势动画

Android中通常使用ScrollView类来实现滚动(scroll)。任何可能超过父类边界的布局都应该嵌套在一个ScrollView中,以提供一个由系统框架管理的可滚动的view。仅仅在某些特殊情形下,才需要实现一个自定义scroller。本节课程描述了这样一个情形:使用scrollers显示滚动效果来响应触摸手势。

你可以使用scrollers(Scroller或者OverScroller)收集数据,这些数据可用来产生滚动动画以响应一个触摸事件。这两个类很相似,但是OverScroller有一些函数,在平移或惯性滑动手势后,能向用户指出他们已经达到内容尽头了。InteractiveChart例子使用了EdgeEffect类(实际上是EdgeEffectCompat类),用来在用户到达内容尽头时显示发光效果。

注意:比起Scroller类,我们更推荐使用OverScroller类来产生滚动动画。OverScroller类为老设备提供了很好的向后兼容性。 另外需要注意的是,当你自己实现滚动时,通常只需要使用scrollers。如果你把布局嵌套在ScrollViewHorizontalScrollView中,它们会帮你把这些做好。

通过使用平台标准的滚动物理定律(摩擦、速度等),scroller可随着时间产生滚动动画。实际上,scroller本身不会绘制任何东西。Scrollers只是随着时间的推移帮你追踪滚动的偏移量,但它们不会自动地把这些位置应用到你的view上。你需要以某种让你的滚动动画更流畅的速度,来获取并使用新的坐标。

理解术语Scrolling

在Android中,“Scrolling”这个词根据不同情景有着不同的含义。

Scrolling是指视窗(viewport)(指你正在看的内容所在的‘窗口’)移动的一般过程。当朝x轴和y轴方向滚动时,就叫做平移。示例程序提供的InteractiveChart类,展示了两种不同类型的scrolling,即拖拽与快速滑动。

虽然经常会把使用scroller对象与快速滑动手势结合起来,但在任何你想让UI展示scrolling动画来响应触摸事件的地方,他们都可以被拿来使用。比如,你可以重写onTouchEvent()函数,来直接处理触摸事件,并且产生一个scrolling效果或“对齐到页”动画(snapping to page)来响应这些触摸事件。

实现基于触摸的Scrolling

本节讲述如何使用一个scroller。下面的代码段来自InteractiveChart样例的类中。它使用了[GestureDetector][GestureDetector_url],并且重写了GestureDetector.SimpleOnGestureListeneronFling()函数。它使用OverScroller来追踪快速滑动手势。在快速滑动手势完成后,如果用户到达内容尽头,应用会显示发光的效果。

注意:InteractiveChart样例程序展示了一个可缩放、平移、滑动的表格。在接下来的代码段中,mContentRect表示view中的一块方形坐标区域,该区域将被用来绘制表格。在任意给定的时间点,整个表格都有某一部分会被绘制在这个区域内。mCurrentViewport表示表格中当前在屏幕上可见的那一部分。因为像素偏移量通常当作整型处理,所以mContentRectRect类型的。因为图表的区域范围是数值型/浮点型值,所以mCurrentViewportRectF类型的。

代码段的第一部分展示了onFling()函数的实现:

//当前视窗(viewport)。这个矩形表示图表当前的可视区域范围。 //视窗是app中用户可通过触摸手势操作的那部分。 private RectF mCurrentViewport = new RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX);

// The current destination rectangle (in pixel coordinates) into which the
// chart data should be drawn.
private Rect mContentRect;

private OverScroller mScroller;
private RectF mScrollerStartViewport;
...
private final GestureDetector.SimpleOnGestureListener mGestureListener
		= new GestureDetector.SimpleOnGestureListener() {
	@Override
	public boolean onDown(MotionEvent e) {
		// Initiates the decay phase of any active edge effects.
		releaseEdgeEffects();
		mScrollerStartViewport.set(mCurrentViewport);
		// Aborts any active scroll animations and invalidates.
		mScroller.forceFinished(true);
		ViewCompat.postInvalidateOnAnimation(InteractiveLineGraphView.this);
		return true;
	}
	...
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2,
			float velocityX, float velocityY) {
		fling((int) -velocityX, (int) -velocityY);
		return true;
	}
};

private void fling(int velocityX, int velocityY) {
	// Initiates the decay phase of any active edge effects.
	releaseEdgeEffects();
	// Flings use math in pixels (as opposed to math based on the viewport).
	Point surfaceSize = computeScrollSurfaceSize();
	mScrollerStartViewport.set(mCurrentViewport);
	int startX = (int) (surfaceSize.x * (mScrollerStartViewport.left -
			AXIS_X_MIN) / (
			AXIS_X_MAX - AXIS_X_MIN));
	int startY = (int) (surfaceSize.y * (AXIS_Y_MAX -
			mScrollerStartViewport.bottom) / (
			AXIS_Y_MAX - AXIS_Y_MIN));
	// Before flinging, aborts the current animation.
	mScroller.forceFinished(true);
	// Begins the animation
	mScroller.fling(
			// Current scroll position
			startX,
			startY,
			velocityX,
			velocityY,
			/*
			 * Minimum and maximum scroll positions. The minimum scroll
			 * position is generally zero and the maximum scroll position
			 * is generally the content size less the screen size. So if the
			 * content width is 1000 pixels and the screen width is 200
			 * pixels, the maximum scroll offset should be 800 pixels.
			 */
			0, surfaceSize.x - mContentRect.width(),
			0, surfaceSize.y - mContentRect.height(),
			// The edges of the content. This comes into play when using
			// the EdgeEffect class to draw "glow" overlays.
			mContentRect.width() / 2,
			mContentRect.height() / 2);
	// Invalidates to trigger computeScroll()
	ViewCompat.postInvalidateOnAnimation(this);
}

onFling()函数调用postInvalidateOnAnimation()时,它会触发computeScroll()来更新x、y的值。通常一个子view用scroller对象来产生滚动动画时会这样做,就如上面的例子一样。

大多数views直接通过scrollTo()函数传递scroller对象的x、y坐标值。接下来的computeScroll()函数的实现采用了一种不同的方式。它调用computeScrollOffset()函数来获得当前位置的x、y值。当满足边缘显示发光效果的条件时(图表已被放大显示,x或y值超过边界,并且app当前没有显示overscroll),这段代码会设置overscroll发光效果,并调用postInvalidateOnAnimation()函数来让view失效重绘:

// Edge effect / overscroll tracking objects.
private EdgeEffectCompat mEdgeEffectTop;
private EdgeEffectCompat mEdgeEffectBottom;
private EdgeEffectCompat mEdgeEffectLeft;
private EdgeEffectCompat mEdgeEffectRight;

private boolean mEdgeEffectTopActive;
private boolean mEdgeEffectBottomActive;
private boolean mEdgeEffectLeftActive;
private boolean mEdgeEffectRightActive;

@Override
public void computeScroll() {
	super.computeScroll();

	boolean needsInvalidate = false;

	// The scroller isn't finished, meaning a fling or programmatic pan
	// operation is currently active.
	if (mScroller.computeScrollOffset()) {
		Point surfaceSize = computeScrollSurfaceSize();
		int currX = mScroller.getCurrX();
		int currY = mScroller.getCurrY();

		boolean canScrollX = (mCurrentViewport.left > AXIS_X_MIN
				|| mCurrentViewport.right < AXIS_X_MAX);
		boolean canScrollY = (mCurrentViewport.top > AXIS_Y_MIN
				|| mCurrentViewport.bottom < AXIS_Y_MAX);

		/*
		 * If you are zoomed in and currX or currY is
		 * outside of bounds and you're not already
		 * showing overscroll, then render the overscroll
		 * glow edge effect.
		 */
		if (canScrollX
				&& currX < 0
				&& mEdgeEffectLeft.isFinished()
				&& !mEdgeEffectLeftActive) {
			mEdgeEffectLeft.onAbsorb((int)
					OverScrollerCompat.getCurrVelocity(mScroller));
			mEdgeEffectLeftActive = true;
			needsInvalidate = true;
		} else if (canScrollX
				&& currX > (surfaceSize.x - mContentRect.width())
				&& mEdgeEffectRight.isFinished()
				&& !mEdgeEffectRightActive) {
			mEdgeEffectRight.onAbsorb((int)
					OverScrollerCompat.getCurrVelocity(mScroller));
			mEdgeEffectRightActive = true;
			needsInvalidate = true;
		}

		if (canScrollY
				&& currY < 0
				&& mEdgeEffectTop.isFinished()
				&& !mEdgeEffectTopActive) {
			mEdgeEffectTop.onAbsorb((int)
					OverScrollerCompat.getCurrVelocity(mScroller));
			mEdgeEffectTopActive = true;
			needsInvalidate = true;
		} else if (canScrollY
				&& currY > (surfaceSize.y - mContentRect.height())
				&& mEdgeEffectBottom.isFinished()
				&& !mEdgeEffectBottomActive) {
			mEdgeEffectBottom.onAbsorb((int)
					OverScrollerCompat.getCurrVelocity(mScroller));
			mEdgeEffectBottomActive = true;
			needsInvalidate = true;
		}
		...
	}

这是缩放部分的代码:

// Custom object that is functionally similar to Scroller
Zoomer mZoomer;
private PointF mZoomFocalPoint = new PointF();
...

// If a zoom is in progress (either programmatically or via double
// touch), performs the zoom.
if (mZoomer.computeZoom()) {
	float newWidth = (1f - mZoomer.getCurrZoom()) *
			mScrollerStartViewport.width();
	float newHeight = (1f - mZoomer.getCurrZoom()) *
			mScrollerStartViewport.height();
	float pointWithinViewportX = (mZoomFocalPoint.x -
			mScrollerStartViewport.left)
			/ mScrollerStartViewport.width();
	float pointWithinViewportY = (mZoomFocalPoint.y -
			mScrollerStartViewport.top)
			/ mScrollerStartViewport.height();
	mCurrentViewport.set(
			mZoomFocalPoint.x - newWidth * pointWithinViewportX,
			mZoomFocalPoint.y - newHeight * pointWithinViewportY,
			mZoomFocalPoint.x + newWidth * (1 - pointWithinViewportX),
			mZoomFocalPoint.y + newHeight * (1 - pointWithinViewportY));
	constrainViewport();
	needsInvalidate = true;
}
if (needsInvalidate) {
	ViewCompat.postInvalidateOnAnimation(this);
}

这是上面代码段中调用过的computeScrollSurfaceSize()函数。他会计算当前可滚动部分的尺寸,以像素为单位。举例来说,如果整个图表区域都是可见的,它的值就简单地等于mContentRect的大小。如果图表两个方向上都放大到200%,此函数返回的尺寸在水平、垂直方向上都会大两倍。

private Point computeScrollSurfaceSize() {
	return new Point(
			(int) (mContentRect.width() * (AXIS_X_MAX - AXIS_X_MIN)
					/ mCurrentViewport.width()),
			(int) (mContentRect.height() * (AXIS_Y_MAX - AXIS_Y_MIN)
					/ mCurrentViewport.height()));
}

查看ViewPager类的源代码,可以发现另一个关于scroller的用法示例。它用滚动来响应flings,使用scrolling来实现“对齐到页”(snapping to page)动画。